package com.easyOrder.core.json.probe;

import com.easyOrder.core.exception.api.InvalidOprationException;
import com.easyOrder.core.utils.ConvertUtil;
import com.easyOrder.core.utils.NameUtil;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Method;

public class Property {
	private String name;

	private Method getter;

	private Method setter;

	Property(Method getter, Method setter) {
		this.getter = getter;
		this.setter = setter;
		name = NameUtil.toCamel(StringUtils.substring(getter.getName(),
				ProbeInfo.GetterPrefix.length()));
	}

	public String getName() {
		return name;
	}

	public Class<?> getMemberType() {
		return getter.getReturnType();
	}

	public java.lang.reflect.Type getGenericMemberType() {
		return getter.getGenericReturnType();
	}

	public Object getValue(Object obj) {
		try {
			return getter.invoke(obj, new Object[] {});
		} catch (Exception e) {
			throw new InvalidOprationException(e.getMessage());
		}
	}

	public void setValue(Object obj, Object value) {
		if (null == setter) {
			throw new InvalidOprationException();
		}
		try {
			setter.invoke(
					obj,
					new Object[] { null != value ? ConvertUtil.changeType(
							(String) value, getter.getReturnType()) : null });
		} catch (Exception e) {
			throw new InvalidOprationException(e.getMessage());
		}
	}
}
